//index.js
const Controllers = require('../controllers/Controller.js').controller;
const controllers = require('../controllers/controllerIndex.js').controller;

//员工鉴权
const shopStaffHavePower = require("../../utils/pattern").shopStaffHavePower

//引入 tabber.js
const getRedirectToURI = require("../../utils/tabber").getRedirectToURI

const app = getApp();
Page({
  data: {
    list: [],
    showConcatDot: false,
    showShareholderDot: false,
    showAppointmentDot: false,
    isFinishShopMsg: true,
    isFirst: true,
    routers: [{
        id: "gl",
        name: '用户管理',
        icon: "/images/home_icon_02.png",
      },
      {
        id: "yy",
        name: '预约管理',
        icon: "/images/home_icon03f.png",
      },
      {
        id: "dd",
        name: '订单管理',
        icon: "/images/home_icon_03.png",
      },
      {
        id: "hx",
        name: '核销记录',
        icon: "/images/home_icon_3f.png",
      },
      {
        name: '记账',
        id: "jz",
        icon: "/images/home_icon_01.png",
      }
    ],
    managerGrop: [

      {
        id: "material",
        name: '轮播图设置',
        icon: "/images/home_icon_04.png",
      }, {
        id: "goodsmanage",
        name: '上架商品',
        icon: "/images/home_icon_05.png",
      },
      {
        name: '员工管理',
        id: "personManager",
        icon: "/images/home_icon_09.png",
      },
      {
        name: '云商城',
        id: "cloudGoods",
        icon: "/images/home_icon_11.png",
      },
    ],
    managerGrop2: [{
        name: '店铺活动',
        id: "shopActive",
        icon: "/images/home_icon_07.png",
      },
      {
        name: '商圈活动',
        id: "tradingArea",
        icon: "/images/icon_BusinessActivities.png",
      },
      {
        name: '股东管理',
        id: "shareholder",
        icon: "/images/ls216@2x.png",
      },
      {
        name: '评价回复',
        id: "hf",
        icon: "/images/hf217@2x.png",
      },
      {
        name: '店铺客服',
        id: "kf",
        icon: "/images/concat@2x.png",
      }
    ],
    managerGrop3: [{
        name: '订单统计',
        id: "dds",
        icon: "/images/dds.png",
      },
      {
        name: '用户统计',
        id: "yhs",
        icon: "/images/yhs.png",
      },
      {
        name: '营业统计',
        id: "yys",
        icon: "/images/yys.png",
      },
      {
        name: '资金流水',
        id: "zjs",
        icon: "/images/zjs.png",
      }
    ],
    openDiscount: "",
    storeInfo: {},
  },
  onLoad(option) {
    let that = this
    this.setData({
      diantype: wx.getStorageSync('diantype')
    })
    if (wx.getStorageSync('diantype') == 1) {
      this.setData({
        list: app.globalData.list
      })
    } else {
      this.setData({
        list: app.globalData.list02,
        power: wx.getStorageSync('power')
      })
    }
  },

  DateDiff(sDate1, sDate2) { //sDate1和sDate2是yyyy-MM-dd格式 
    console.log('octo' + sDate1, sDate2)
    var aDate, oDate1, oDate2, iDays;
    aDate = sDate1.split("-");
    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]); //转换为yyyy-MM-dd格式 
    aDate = sDate2.substring(0, 10).split("-");
    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数 
    return iDays; //返回相差天数 
  },
  onShow() {
    //获取token
    let token = wx.getStorageSync('token') || '';
    let that = this
    //优先判断token
    if (token) {} else {
      //无token，直接登录
      // this.GetLogin();
      wx.reLaunch({
        url: '/pages/login/index',
      })
    }
    this.getShopMsg()
  },
  //获取店铺首页信息
  getShopMsg() {
    let that = this
    controllers.shopInfo({
      sessionId: wx.getStorageSync('token'),
      shopId: wx.getStorageSync('shopId')
    }).then(res => {

      let newTime = new Date().getTime();
      let lastDay = 0;
      if (res.data.endTime) {

        let endTime = new Date(res.data.endTime.replace(/-/g, "/")).getTime();
        lastDay = Math.ceil((endTime - newTime) / 1000 / 24 / 3600);


        that.setData({
          lastDay
        })
        console.log(lastDay)
        // 是否可上传视频 videoNumLimit(视频上限)和videoNum(当前视频数)
        const isLimitVideo = res.data.videoNumLimit > res.data.videoNum
        
        wx.setStorageSync('isLimitVideo', isLimitVideo)
        wx.setStorageSync('endTime', res.data.endTime)
        wx.setStorageSync('shopGroupEndTime', res.data.shopGroupEndTime)
      }
      // 前往续费
      if ((lastDay < 0 || !res.data.endTime) && res.data.state == 1 && this.data.isFirst) {
        this.setData({
          isFirst: false,
        })
        wx.showModal({
          title: "您还没有开通店铺功能",
          confirmText: "前往开通",
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/Index/bill/bill?type=0',
              })
            }
          }
        })

      }
      // 店铺是否完善
      if (!res.data.idImg || !res.data.idBackImg || !res.data.businessImg) {
        this.setData({
          isFinishShopMsg: false,
        })
      } else {
        this.setData({
          isFinishShopMsg: true,
        })
      }
      that.setData({
        storeInfo: res.data,

      })
      wx.setStorageSync('typeId', res.data.typeId)
      wx.setStorageSync('shopImg', res.data.shopImg)
      this.getShopDiscount()

      if (res.data.shopGroupEndTime) {
        let shopGroupEndTime = res.data.shopGroupEndTime.replace(/-/g, "/")
        if (shopGroupEndTime) {
          if (new Date(shopGroupEndTime).getTime() > newTime) {
            this.setData({
              Effective: true
            })
            wx.setStorageSync('Effective', true)
          } else {
            this.setData({
              Effective: false
            })
            wx.setStorageSync('Effective', false)
          }
        }
      } else {
        this.setData({
          Effective: false
        })
        wx.setStorageSync('Effective', false)
      }
      // 判断是否有股东提现
      let showShareholderDot = res.data.beanExamineNum > 0 ? true : false
      // 判断是否有客服信息
      let showConcatDot = res.data.suggestNum > 0 ? true : false
      this.setData({
        showConcatDot,
        showShareholderDot
      })
      wx.setStorageSync('shareholdersWithdrawal', showShareholderDot)

      // 预约管理提醒
      let showAppointmentDot = res.data.agreeNum > 0 ? true : false
      this.setData({
        showAppointmentDot
      })

    })
  },
  //跳转续费页面
  toBill() {
    wx.requestSubscribeMessage({
      tmplIds: ["fleQPapATpp6thoxCxBw1NSkonsBPrLbeow939kr4bo", "Sc3aovgRuyAjgHPCxz2tKwY1udcPno6ZabDj72J5VFo", "EK0YhGfRv3PZL5sY9jLOI54XskmKQ3B4aQN1x26rMZQ"],
      success: res => {
        console.log(res);
      },
      complete: res => {
        wx.navigateTo({
          url: '/pages/Index/RechargeList/RechargeList',
        })
      }
    })
  },
  tabChange(e) {
    let index = e.detail.index;
    getRedirectToURI(index)
  },
  login() {
    //获取数据
    Controllers.login().then(res => {

    })
  },
  //跳转
  routerToPage(res) {
    console.log(res)
    switch (res.currentTarget.dataset.id) {
      case 'sy':
        wx.navigateTo({
          url: "../settlement/CashierCheckout/CashierCheckout"
        })
        break;
      case 'shopActive':
        wx.navigateTo({
          url: "/pages/Index/shopActive/index"
        })
        break;
      case 'jz':
        if (shopStaffHavePower(this.data.power, 'BOOK') || this.data.diantype == 1) {
          wx.navigateTo({
            url: "../Accounts/AccountsIndex/AccountsIndex"
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case 'yy':
        if (shopStaffHavePower(this.data.power, 'ORDER') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/order/appointment-record/appointment-record',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case 'dd':
        if (shopStaffHavePower(this.data.power, 'ORDER') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/order/management-order/management-order',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case 'vipSetting':
        wx.navigateTo({
          url: "/pages/goodsManagement/OfflineSetVip/OfflineSetVip"
        })
        break;
      case 'gl':
        if (shopStaffHavePower(this.data.power, 'USER') || this.data.diantype == 1) {
          wx.navigateTo({
            url: "../userStatistics/Userindex/UserIndex"
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case 'changeStore':
        wx.navigateTo({
          url: '/pages/login/select_store/index',
        })
        break;
      case 'tradingArea':
        if (this.data.Effective != true) {
          if (this.data.diantype == 1) {
            wx.showModal({
              title: '提示',
              content: '一卡通未续费或者已到期,请前往一卡通续费',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/Index/bill/bill?type=1',
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          } else {
            wx.showToast({
              icon: "none",
              title: '一卡通未续费或者已到期,请联系店长进行续费',
            })
          }
          return
        }

        if (shopStaffHavePower(this.data.power, 'GROUP') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/tradingArea/tradingArea',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }

        break;
      case 'userManager':
        wx.navigateTo({
          url: '/pages/userStatistics/SetIndex/setIndex',
        })
        break;
      case 'personManager':
        if (shopStaffHavePower(this.data.power, 'STAFF') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/userStatistics/Personnel/Personnel',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "goodsmanage":
        if (shopStaffHavePower(this.data.power, 'GOODS') || this.data.diantype == 1) {
          if (this.data.isFinishShopMsg) {
            wx.navigateTo({
              url: '/pages/goodsManagement/goodsManagementIndex/goodsManagementIndex',
            })
          } else {
            wx.showModal({
              title: '您的店铺信息需要完善',
              confirmText: '去完善',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/settlement/index?isReplenish=1',
                    // url: '/pages/settlement/index?scene='+'1,2,1',
                  })
                }
              }
            })
          }

        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "material":
        if (shopStaffHavePower(this.data.power, 'ROTATION') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/material/index',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "cloudGoods":
        if (shopStaffHavePower(this.data.power, 'GOODS') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/cloudGoods/index',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
        // case "capitalFlow":
        //   wx.navigateTo({
        //     url: '/pages/my/my_account/index',
        //   })
        //   break;
      case "shareholder":
        if (shopStaffHavePower(this.data.power, 'USER') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/Index/shareholderManage/shareholderManage',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "cloudGoods":
        wx.navigateTo({
          url: '/pages/cloudGoods/index',
        })
        break;
      case "hf":
        if (shopStaffHavePower(this.data.power, 'COMMENT') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/Index/myCommentList/myCommentList',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "kf":
        if (wx.getStorageSync('diantype') == 1) {
          wx.navigateTo({
            url: "/pages/my/my_userFeelBack/index"
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "hx":
        if (shopStaffHavePower(this.data.power, 'WRITE_OFF') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/Index/cashOutHistory/cashOutHistory',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "dds":
        if (shopStaffHavePower(this.data.power, 'ORDER') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/order/management-order/management-order',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "yhs":
        if (shopStaffHavePower(this.data.power, 'USER') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/Index/userStatistics/userStatistics',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "yys":
        if (shopStaffHavePower(this.data.power, 'REVENUE') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/Index/businessStatistics/businessStatistics?storeInfo=' + JSON.stringify(this.data.storeInfo),
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
      case "zjs":
        if (shopStaffHavePower(this.data.power, 'REVENUE') || this.data.diantype == 1) {
          wx.navigateTo({
            url: '/pages/Index/transactionRecord/transactionRecord',
          })
        } else {
          wx.showToast({
            icon: "none",
            title: '暂无该权限',
          })
        }
        break;
    }
  },

  //跳转订单管理
  toOrdeTypeManage() {
    wx.navigateTo({
      url: '/pages/order/management-order/management-order',
    })
  },

  toDetail(options) {
    let id = options.currentTarget.dataset.id;
    let time = ""
    if (options.currentTarget.dataset.time) {
      time = options.currentTarget.dataset.time
    }
    if (id == 0) {
      wx.navigateTo({
        url: '/pages/userStatistics/Userindex/UserIndex?time=' + time,
      })
    } else {
      wx.navigateTo({
        url: '/pages/Index/transactionRecord/transactionRecord',
      })
    }
  },

  //获取折扣是否开启
  getShopDiscount() {
    Controllers.shopDiscount({
      shopId: wx.getStorageSync('shopId')
    }).then(res => {
      this.setData({
        openDiscount: res.data.openDiscount
      })
      wx.setStorageSync('openDiscount', res.data.openDiscount)
    })
  },
  // 变更店铺头像
  changeShopImg() {
    let that = this;
    wx.showModal({
      content: '确认更换店铺头像',
      confirmText: "更换",
      success(res) {
        if (res.confirm) {
          that.chooseImage()
        }
      }
    })

  },
  chooseImage() {
    let that = this;
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: "https://www.xlshhr.com/beauty-industry/api/img/uploadFile",
          filePath: tempFilePaths[0],
          name: 'image',
          formData: {
            'sessionId': wx.getStorageSync('token')
          },
          success(res) {
            console.log(res);
            // const data = res.date
            let src = JSON.parse(res.data).data
            let value = {
              shopId: wx.getStorageSync('shopId'),
              shopImg: src,
            }
            Controllers.updateShopMsg(value).then(res => {
              wx.showToast({
                title: '操作成功',
              })
              that.getShopMsg()
            })
          }
        })
      }
    })
  }
})